require 'digest/sha2'

class User < ActiveRecord::Base
	validates_presence_of  :username, :email
	validates_uniqueness_of :username, :message => "Login nie jest unikalny!"
	#validates_uniqueness_of :full_name
	validates_uniqueness_of :email, :message => "Email nie jest unikalny!"
	attr_accessor :password_confirmation
	attr_accessor :current_password
	validates_confirmation_of :password, :message => "Hasło nie potwierdzone!"
	
	#validates_format_of :email,
	#					:with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i,
#
	#					:message => "Musi byc prawidlowy format adresu email."
	validate :password_non_blank
	
	has_many :comments, :dependent => :destroy
	has_many :pictures, :dependent => :destroy
	has_many :votes, :dependent => :destroy
	
	def self.authenticate(username, password)
		user = self.find_by_username(username)
		if user
			exp_passwd = Digest::SHA256.hexdigest(password + user.password_salt)
			if user.password_hash != exp_passwd
				user = nil
			end	
		end
		user	
	end
	
	def self.admin?(id)
		user = self.find_by_id(id)
		if user.is_admin
			@admin = user
		else
			@admin = nil
		end
		@admin
	end	
	
	def password
		@password
	end
	
	def clear_password!
		self.password = nil
		self.password_confirmation = nil
		self.current_password = nil
	end
	
	def full_name
		@full_name = [name, surname].join(' ')
	end

	def nick_or_full_name
		if full_name != ' '
			@name = full_name
		else
			@name = self.username
		end
	end
	
	def location
		if (self.city != '') and (self.country != '')
			@location = self.city + ', ' + self.country
		elsif self.city != ''
			@location = self.city
		elsif self.country != ''
			@location = self.country
		else
			@location = ''
		end
	end
	
	def password=(pass)
		if pass != nil
			@password = pass
			salt = [Array.new(6){rand(256).chr}.join].pack("m").chomp
			self.password_salt, self.password_hash = salt, Digest::SHA256.hexdigest(pass + salt)
		else
			return
		end
	end
	
	def correct_password?(params)
		current_password = Digest::SHA256.hexdigest(params[:user][:current_password]+self.password_salt)
		self.password_hash == current_password
	end
	
	def password_errors(params)
		self.password = params[:user][:password]
		self.password_confirmation = params[:user][:password_confirmation]
		valid?
		errors.add("Obecne hasło jest niepoprawne!")
	end
	
private

	def password_non_blank
		(errors.add_to_base("Brak hasła") if password.blank?) unless self.id
	end
	
end